package com.lysj.website.common.conver;


import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.lysj.website.common.web.ParamUtil;

import java.io.IOException;
import java.math.BigDecimal;

/**
 * @author Created by zk on 2019-07-03 20:03
 * @description 返回给前端的数值，保留后两位--钱
 */
public class MoneyJsonSerializer extends JsonSerializer<BigDecimal> {

    public static BigDecimal moneySerialize(BigDecimal value) {
        return value.setScale(2, BigDecimal.ROUND_DOWN);
    }

    public static String moneySerializeToString(BigDecimal value) {
        return moneySerialize(value).stripTrailingZeros().toPlainString();
    }

    @Override
    public void serialize(BigDecimal bigDecimal, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
        if (ParamUtil.isBlank(bigDecimal)) {
            jsonGenerator.writeString("0");
        } else {
            jsonGenerator.writeString(moneySerializeToString(bigDecimal));
        }
    }
}
